<template>
  <view class="container">
    <view class="form">
      <view class="form-item">
        <input type="text" placeholder="用户名" @input="bindUsernameInput" />
      </view>
      <view class="form-item">
        <input type="password" placeholder="密码" @input="bindPasswordInput" />
      </view>
      <view class="form-item">
        <input type="password" placeholder="确认密码" @input="bindConfirmPasswordInput" />
      </view>
      <view class="form-item">
        <input type="text" placeholder="头像URL" @input="bindAvatarInput" />
      </view>
      <button @tap="register">注册</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      confirmPassword: '',
      avatar: ''
    };
  },
  methods: {
    bindUsernameInput(e) {
      this.username = e.detail.value;
    },
    bindPasswordInput(e) {
      this.password = e.detail.value;
    },
    bindConfirmPasswordInput(e) {
      this.confirmPassword = e.detail.value;
    },
    bindAvatarInput(e) {
      this.avatar = e.detail.value;
    },
    register() {
      if (!this.username || !this.password || !this.confirmPassword || !this.avatar) {
        uni.showToast({
          title: '用户名、密码、确认密码和头像不能为空',
          icon: 'none'
        });
        return;
      }
      if (this.password !== this.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        });
        return;
      }
      // 构建注册请求的URL
      const registerUrl = `http://127.0.0.1:8081/insertuser/?name=${encodeURIComponent(this.username)}&user=${encodeURIComponent(this.username)}&password=${encodeURIComponent(this.password)}&img=${encodeURIComponent(this.avatar)}`; 
      uni.request({
        url: registerUrl,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: '注册成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '注册失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    }
  }
}
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.form {
  width: 90%;
}

.form-item {
  margin-bottom: 20rpx;
}

input {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10rpx;
  width: 100%;
}

button {
  background-color: #1AAD19;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10rpx;
  width: 100%;
}
</style>